package com.jdaoyun.execute;


import cn.hutool.core.util.ObjectUtil;
import com.jdaoyun.a_empcsApi.service.TCarInfoService;
import com.jdaoyun.a_empcsApi.service.TDriverInfoService;
import com.jdaoyun.a_empcsApi.service.TMedicalStaffService;
import com.jdaoyun.util.StartupTaskCondition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;


import java.util.concurrent.CompletableFuture;


/**
 * 首次全量化推送
 */
@Component
@Conditional(StartupTaskCondition.class) // 添加条件注解,配置中位true时，被spring管理
@Slf4j
public class StartupTaskRunner implements ApplicationRunner {


    @Autowired
    private PushCode pushCode;//推送代码

    @Autowired
    private Search search;//搜索存表

    @Autowired
    private TCarInfoService carInfoService;

    @Autowired
    private TDriverInfoService driverInfoService;

    @Autowired
    private TMedicalStaffService medicalStaffService;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("项目启动，开始执行初始化任务...");
        // 使用 CompletableFuture 确保任务按顺序执行
        CompletableFuture.runAsync(() -> {
            log.info("开始执行机构数据推送...");
            pushCode.orgInfo();
        }).thenRunAsync(() -> {
            if (ObjectUtil.isNotEmpty(carInfoService.list())) {//不是空的才执行
                carInfoService.remove(null);
            }
            search.carInfo();
            if (ObjectUtil.isNotEmpty(driverInfoService.list())) {//不是空的才执行
                driverInfoService.remove(null);
            }
            if (ObjectUtil.isNotEmpty(medicalStaffService.list())) {//不是空的才执行
                medicalStaffService.remove(null);
            }
            search.driver_Doctor_Nurse();
            search.vehicleRealTimeLocation();
            search.rescueRecordAgencyTime();
            search.emergencyAgencyTime();
            search.emergencyRecordTaskTime();
            search.emergencyRecordTaskDiagnosis();
        }).thenRunAsync(() -> {

        }).exceptionally(ex -> {
            log.error("初始化任务执行失败：{}", ex.getMessage(), ex);
            return null;
        }).join(); // 阻塞主线程直到所有任务完成

        log.info("所有初始化任务执行完成！");


    }


}
